package com.beigai.imessage.filter;

import com.beigai.imessage.server.UserSession;
import com.beigai.imessage.session.CurrentUserSession;
import com.beigai.imessage.session.MemorySessionCache;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by xxl on 2017/5/18.
 * 登录拦截
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        Cookie[] cookies = req.getCookies();
        if (cookies == null) {
            chain.doFilter(request, response);
            return;
        }
        String sessiond = null;
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if ("sessionId".equals(cookieName)) {
                sessiond = cookie.getValue();
                break;
            }
        }
        if (sessiond != null) {
            UserSession session = MemorySessionCache.getInstance().getSession(sessiond);
            CurrentUserSession.set(session);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
